///**
// * Created by YHQ on 2016-03-22.
// */
angular.module('hyt.userService', [])


  .factory('Storage', function() {
    return {
      set: function(key, data) {
        return window.localStorage.setItem(key, window.JSON.stringify(data));
      },
      get: function(key) {

        return window.JSON.parse(window.localStorage.getItem(key));
      },
      remove: function(key) {
        return window.localStorage.removeItem(key);
      }
    };
  })

    //用户注册
  .factory('Regist',function($resource,$rootScope,ENV){
    var APIUrl = ENV.api, user, result1,result2;
    var fwqbs=ENV.fwqbs;
    var resource=$resource(APIUrl);
    return{
      //判断用户是否存在（判断手机号）
      checkExist:function(sjhm){
        return resource.save({
          ACTION_NAME:'chooseBiz.rePhone',
          ACTION_INFO:{
            'lxdh':sjhm,
            'sfwlgs':"1"
          }
        },function(response){
          result1=response;
          //广播账户是否存在结果
          $rootScope.$broadcast('Check.CheckUser');
        });
      },
      checkExist2:function(sjhm){
        return resource.save({
          ACTION_NAME:'chooseBiz.rePhone',
          ACTION_INFO:{
            'lxdh':sjhm,
            'sfwlgs':"1"
          }
        },function(response){
          result2=response;
          //广播账户是否存在结果
          $rootScope.$broadcast('Check2.CheckUser');
        });
      },
      //发送请求获得验证码
      getYzmCode:function(sjhm){
        return resource.save({
          ACTION_NAME:'chooseBiz.sendDx',
          ACTION_INFO:{
            phone:sjhm
          }
        },function(resp){
          var codeResult=resp;
          var codeyzm=codeResult.ACTION_INFO.yzm;
          console.log(codeResult);
          console.log(codeyzm);
        });
      },
      //注册
      regist:function(lxdh,pwd,yzm,yhlx){
        return resource.save({
          ACTION_NAME:'chooseBiz.trueRegister',
          ACTION_INFO:{
            'fwqbs':fwqbs,
            'pwd':pwd,
            'yhlx':yhlx,
            'lxdh':lxdh,
            'sfwlgs':'0',
            'yzm':yzm
          }
        },function(resp){
          user=resp;
          console.log(user);
          $rootScope.$broadcast('Regist.RegistUser');
        });
      },
      getUser: function(){
        return user;
      },
      getResult:function(){
        return result1;
      },
      getResult2:function(){
        return result2;
      }
    }
  })
    //判断sid
    .factory('Judge',function($resource,$rootScope,ENV,Storage){
      var APIUrl = Storage.get('fwqdz');

      var resource = $resource(APIUrl);
      var JudgeJson;
      return {
        judgeSid: function(sid,user_id,yh_id,sfwlgs,dw_id) {
          return resource.save({
            ACTION_NAME:'loginBiz.hiddenLogin',
            ACTION_INFO:{
              'yh_id':yh_id,
              'sfwlgs':sfwlgs,
              'dw_id':dw_id
            },
            SID:sid,
            USER_ID:user_id
          }, function(response) {
            //console.log(response);
            JudgeJson=response;
            console.log(JudgeJson);
            $rootScope.$broadcast('Judge.judgeUpdated');
          });
        },
        //返回结果
        getJudgeResult: function(){
          return JudgeJson;
        }
      };
    })



    //用户登录
  .factory('User', function($resource, $rootScope,ENV,Storage) {
    var APIUrl = ENV.api;
    var fwqbs=ENV.fwqbs;
    var user;
    var storageKey='user';
    var resource = $resource(APIUrl);
    var jsonObj="";
    //console.log(resource);
    return {
      login: function(sjhm,pwd,sfwlgs) {
        return resource.save({
        ACTION_NAME:'chooseBiz.trueLogin',
        ACTION_INFO:{
            'lxdh':sjhm,
            'pwd':pwd,
            'sfwlgs':sfwlgs,
            'fwqbs':fwqbs
          }
        }, function(response) {
          //console.log(response);
          user=response;
          jsonObj=user.ACTION_INFO;
          console.log(jsonObj);
          console.log(user);
          $rootScope.$broadcast('User.loginUpdated');
        });
      },
      //退出登录
      logout: function() {
        user = {};
        Storage.remove(storageKey);
      },
      //返回结果
      getResult: function(){
        return user;
      }
      //getSid:function(){
      //  return user.sid;
      //}
    };
  })
    //验证手机号
    .factory('VerificationFactory',function($resource, $rootScope,ENV){
      var APIUrl = ENV.api,result;
      var fwqbs=ENV.fwqbs;
      var resource = $resource(APIUrl);
      return {
        verification: function(lxdh,sfwlgs,yzm) {
          return resource.save({
            ACTION_NAME:'chooseBiz.firstLogin',
            ACTION_INFO:{
              "lxdh":lxdh,
              "sfwlgs":sfwlgs,
              "yzm":yzm
            }
          }, function(response) {
            result=response;
            $rootScope.$broadcast('Verification.yzm');
          });
        },
        getResult:function(){
          return result;
        }
      };
    })
    //忘记密码
  .factory('ForgetPwdFactory',function($resource, $rootScope,ENV,Storage){
    var APIUrl = ENV.api,userInfo,result,userInfoxiu,resultxiu;
    var fwqbs=ENV.fwqbs;
    var backUrl=Storage.get('fwqdz');
    var resource = $resource(APIUrl);
    var resource1=$resource(backUrl);
    return {
      //忘记密码
      checkUser: function(lxdh) {
        return resource.save({
          ACTION_NAME:'chooseBiz.validateUser',
          ACTION_INFO:{
            'lxdh':lxdh
          }
        }, function(response) {
          userInfo=response;
          console.log(userInfo);
          $rootScope.$broadcast('CheckF.CheckUser');
        });
      },
      getUser:function(){
        return userInfo;
      },
      getYzm:function(lxdh){
        return resource.save({
          ACTION_NAME:'chooseBiz.sendDx',
          ACTION_INFO:{phone:lxdh}
        },function(resp){
          var codeResult=resp;
          var codeyzm=codeResult.ACTION_INFO.yzm;
          console.log(codeResult);
          console.log(codeyzm);
        });
      },
      update:function(pwd,yzm,lxdh,sfwlgs){
        return resource.save({
          ACTION_NAME:'chooseBiz.updatePasswd',
          ACTION_INFO:{
            'sfwlgs':sfwlgs,
            'pwd':pwd,
            'yzm':yzm,
            'lxdh':lxdh,
            'fwqbs':fwqbs
          }
        },function(resp){
          result=resp;
          console.log(result);
          $rootScope.$broadcast('Update.UpdatePwd');
        });
      },
      getResult:function(){
        return result;
      },
      //修改密码
      checkUserxiu: function(lxdh) {
        return resource1.save({
          ACTION_NAME:'loginBiz.validateUser',
          ACTION_INFO:{
            'lxdh':lxdh
          }
        }, function(response) {
          userInfoxiu=response;
          console.log(userInfoxiu);
          $rootScope.$broadcast('Checkxiu.CheckUser');
        });
      },
      getUserxiu:function(){
        return userInfoxiu;
      },
      getYzmxiu:function(lxdh){
        return resource1.save({
          ACTION_NAME:'yanzhengBiz.merge#Dxyz',
          ACTION_INFO:{phone:lxdh}
        },function(resp){
          var codeResult=resp;
          var codeyzm=codeResult.ACTION_INFO.yzm;
          console.log(codeResult);
          console.log(codeyzm);
        });
      },
      updatexiu:function(pwd,yzm,lxdh){
        return resource1.save({
          ACTION_NAME:'yanzhengBiz.updatePasswd#Dxyz',
          ACTION_INFO:{
            'passwd':pwd,
            'yzm':yzm,
            'lxdh':lxdh
          }
        },function(resp){
          resultxiu=resp;
          console.log(resultxiu);
          $rootScope.$broadcast('Updatexiu.UpdatePwd');
        });
      },
      getResultxiu:function(){
        return resultxiu;
      }
    };
  })
    .factory('CheckAPKFactory',function($rootScope,$resource,ENV,Storage){
      var APIUrl = Storage.get('fwqdz'),result,resultApk,resultQuery,resultC,resultC1;
      var resource = $resource(APIUrl);
      return{
        check:function(version_no,sid,user_id,yh_id                                                                                                                                                                                                                          ,dw_id){
          return resource.save({
            SID:sid,
            USER_ID:user_id,
            ACTION_NAME:'sqlKeyBiz.page#version_query',
            ACTION_INFO:{
              'app_type':'1',
              'version_no':version_no,
              'yh_id':yh_id,
              'dw_id':dw_id
            }
          },function(resp){
            result=resp;
            console.log(resp);
            $rootScope.$broadcast('Update.APK');
          });
        },
        getResult:function(){
          return result;
        },
        checkQuery:function(version_no,sid,user_id,yh_id,dw_id){
          return resource.save({
            SID:sid,
            USER_ID:user_id,
            ACTION_NAME:'sqlKeyBiz.page#version_query',
            ACTION_INFO:{
              'app_type':'1',
              'version_no':version_no,
              'yh_id':yh_id,
              'dw_id':dw_id
            }
          },function(resp){
            resultQuery=resp;
            console.log(resp);
            $rootScope.$broadcast('UpdateQuery.APK');
          });
        },
        getResultQuery:function(){
          return resultQuery;
        },
        queryContent:function(sid,user_id,yh_id,dw_id){
          return resource.save({
            SID:sid,
            USER_ID:user_id,
            ACTION_NAME:'sqlKeyBiz.page#updateContent_query',
            ACTION_INFO:{
              'app_type':'1',
              'yh_id':yh_id,
              'dw_id':dw_id
            }
          },function(resp){
            resultC=resp;
            console.log(resp);
            $rootScope.$broadcast('UpdateContent.APK');
          });
        },
        getResultContent:function(){
          return resultC;
        }
      };
    })
   .factory('GenCydhFactory',function($rootScope,$resource,ENV,Storage){
     var APIUrl =  Storage.get('fwqdz'),result,autoResult,checkBox;
     var resource = $resource(APIUrl);
     //初始化toggleButton
     return{
       checkBox:function(sid,user_id,yh_id,zd_id){
         return resource.save({
           SID:sid,
           USER_ID:user_id,
           ACTION_NAME:'sqlKeyBiz.dhzd#dhzd',
           ACTION_INFO:{
             'zd_id':zd_id,
             'yh_id':yh_id
           }
         },function(resp){
           checkBox=resp;
           console.log(resp);
           $rootScope.$broadcast('CheckBox.Cydh');
         });
       },
       getCheckBox:function(){
         return checkBox;
       },
       check:function(sid,user_id,yh_id,zd_id){
         return resource.save({
           SID:sid,
           USER_ID:user_id,
           ACTION_NAME:'sqlKeyBiz.list#queryBmAppSet',
           ACTION_INFO:{
             'id':yh_id+""+zd_id,
             'bm_id':zd_id,
             'yh_id':yh_id
           }
         },function(resp){
           result=resp;
           console.log(resp);
           $rootScope.$broadcast('Check.Cydh');
         });
       },
       getResult:function(){
         return result;
       },
       autoCydh:function(sid,user_id,yh_id,zd_id,dw_id,cyd){
         return resource.save({
           SID:sid,
           USER_ID:user_id,
           ACTION_NAME:'beanBiz.merge#Bm_app_set',
           ACTION_INFO:{
             '_options':{
               'mergeField':'id,bm_id'
             },
             'id':yh_id+""+zd_id,
             'bm_id':zd_id,
             'dw_id':dw_id,
             'cydh_add_type':cyd.type,
             'yh_id':yh_id
           }
         },function(resp){
           autoResult=resp;
           console.log(resp);
           $rootScope.$broadcast('Save.AutoCydh');
         });
       },
       getAutoResult:function(){
         return autoResult;
       }
     };
   })

    //打印设置
    .factory('PrinterFactory',function($rootScope,$resource,ENV,Storage){
      var APIUrl =  Storage.get('fwqdz'),result,set,set1;
      var resource = $resource(APIUrl);
      return{
        saveSet:function(sid,user_id,yh_id,zd_id,sfdyfhrcg,sfdywlgscg,sfdyhwbq,title,kfdh,bz,hwbtdyxw,sfdyxxf){
          return resource.save({
            SID:sid,
            USER_ID:user_id,
            ACTION_NAME:'printBiz.dyInsert',
            ACTION_INFO:{
              'yh_id':yh_id,
              'zd_id':zd_id,
              'bz':bz,
              'gsmc':title,
              'hwbtdyxw':hwbtdyxw,
              'kfdh':kfdh,
              'sfdyfhrcg':sfdyfhrcg,
              'sfdyhwbt':sfdyhwbq,
              'sfdywlgscg':sfdywlgscg,
              'fhrcgfs':'1',
              'wlgscgfs':'1',
              'sfdyxxf':sfdyxxf
            }
          },function(resp){
            result=resp;
            console.log(resp);
            $rootScope.$broadcast('Save.PrintSet');
          });
        },
        getResult:function(){
          return result;
        },
        fetchPrint:function(sid,user_id,yh_id,zd_id){
          return resource.save({
            SID:sid,
            USER_ID:user_id,
            ACTION_NAME:'sqlKeyBiz.dyFetch#dyFetch',
            ACTION_INFO:{
              'yh_id':yh_id,
              'zd_id':zd_id
            }
          },function(resp){
            set=resp;
            console.log(resp);
            $rootScope.$broadcast('Query.PrintSet');
          });
        },
        getSet:function(){
          return set;
        },
        fetchPrint1:function(sid,user_id,yh_id,zd_id){
         return resource.save({
           SID:sid,
           USER_ID:user_id,
           ACTION_NAME:'sqlKeyBiz.dyFetch#dyFetch',
           ACTION_INFO:{
             'yh_id':yh_id,
             'zd_id':zd_id
           }
         },function(resp){
           set1=resp;
           console.log(resp);
           $rootScope.$broadcast('Query1.PrintSet');
         });
        },
        getSet1:function(){
          return set1;
        }
      };
    })
  //站点切换
  .factory('ZdqhFactory',function($resource,$rootScope,ENV,Storage){
    var api =  Storage.get('fwqdz'),result;
    var resource = $resource(api);
    return{
      //站点列表
      zdList:function(sid,yh_id,dw_id,user_id,zd_id){
        return resource.save({
          SID:sid,
          USER_ID:user_id,
          ACTION_NAME :  'sqlKeyBiz.list#bmxx_query_by_zd_id',
          ACTION_INFO : {
            'dw_id':dw_id,
            'zd_id':zd_id,
            'yh_id':yh_id
          }
        },function(r){
          console.log(r);
          if(r.ACTION_RETURN_CODE == "000000") {
            result = r.ACTION_INFO.RESULT_LIST;
            $rootScope.$broadcast('ZdqhData');
          }
        });
      },
      getResult:function(){
        return result;
      }
    }
  })

  //意见反馈
  .factory('FeedbackFactory',function($resource,$rootScope,ENV,Storage){
    var api =  Storage.get('fwqdz'),result;
    var resource = $resource(api);
    return{
      getcontent:function(sid,user_id,yh_id,lxdh,sfwlgs,content){
        return resource.save({
          SID:sid,
          USER_ID:user_id,
          ACTION_NAME :  'sqlKeyBiz.transInsert#fkxxInsert',
          ACTION_INFO : {
            'yh_id':yh_id,
            'lxdh':lxdh,
            'fkxx':content,
            'sfwlgs':sfwlgs
          }
        },function(r){
          if(r.ACTION_RETURN_CODE == "000000") {
            result = r.ACTION_INFO.result;
            $rootScope.$broadcast('FeedbackData');
          }
        });
      },
      getResult:function(){
        return result;
      }
    }
  })
  //联系人选择
    .factory('LinkmanFactory',function($resource,$rootScope,ENV,Storage,$ionicLoading,$state){
      var api =  Storage.get('fwqdz');
      var resource = $resource(api);
      var result;
      var linkmanData={},
          pagesize=10;
      return{
        getcontent:function(sid,user_id,yh_id,dw_id,sflx,khmc,lxdh,pyjm){
          var hasNextPage =true;    //判断是否有下一页
          return resource.save({
            SID:sid,
            USER_ID:user_id,
            ACTION_NAME :  'sqlKeyBiz.page#querykhxx',
            ACTION_INFO : {
              'yh_id':yh_id,
              'dw_id':dw_id,
              'sflx':sflx,
              'khmc':khmc,
              'lxdh':lxdh,
              'pyjm':pyjm,
              'pagesize':'10',
              'current_page':'1'
            }
          },function(r){
            if(r.ACTION_RETURN_CODE == "000000"){
              if(r.ACTION_INFO.RESULT_LIST.length < pagesize){
                hasNextPage = false;
              }

              linkmanData[pagesize] = {
                hasNextPage : hasNextPage,
                'current_page' : 2,
                'data' : r.ACTION_INFO.RESULT_LIST
              };

              $rootScope.$broadcast('LinkmanList.linkUpdated');
            }else if (r.ACTION_RETURN_CODE == "000005"){
              $ionicLoading.show({
                noBackdrop: true,
                template: "您的账号已在其他设备登录",
                duration: 1500
              });
              $state.go("login");
            }
          });
        },
        getLinkman : function(){
          if(linkmanData[pagesize] == undefined){
            return false;
          }
          return linkmanData[pagesize];
        },
        getMoreLink:function(sid,user_id,yh_id,dw_id,sflx,khmc,lxdh,pyjm){
          //为了解决一步加载的时候数据还没有加载完成  然后请求loadMore的时候  找不到数据
          if(linkmanData[pagesize] == undefined){
            return false;
          }

          //获取以前的数据
          var hasNextPage = linkmanData[pagesize].hasNextPage;
          var current_page = linkmanData[pagesize].current_page;
          var moreManListData = linkmanData[pagesize].data;

          resource.save({
            ACTION_NAME: 'sqlKeyBiz.page#querykhxx',
            SID:sid,
            USER_ID:user_id,
            ACTION_INFO : {
              'yh_id':yh_id,
              'dw_id':dw_id,
              'sflx':sflx,
              'khmc':khmc,
              'lxdh':lxdh,
              'pyjm':pyjm,
              'pagesize':pagesize,
              'current_page':current_page
            }
          }, function (r) {

            current_page++;

            if(r.ACTION_RETURN_CODE == "000000"){
              if(r.ACTION_INFO.RESULT_LIST.length < pagesize){
                hasNextPage = false;
              }else if (r.ACTION_RETURN_CODE == "000005"){
                $ionicLoading.show({
                  noBackdrop: true,
                  template: "您的账号已在其他设备登录",
                  duration: 1500
                });
                $state.go("login");
              }

              moreManListData = moreManListData.concat(r.ACTION_INFO.RESULT_LIST);

              linkmanData[pagesize] = {
                hasNextPage : hasNextPage,
                'current_page' : current_page,
                'data' : moreManListData
              };
              $rootScope.$broadcast('LinkmanList.linkUpdated');
            }

          })
        },

        hasNextPage: function() {
          if (linkmanData[pagesize] === undefined) {
            return false;
          }
          return linkmanData[pagesize].hasNextPage;
        },

        getDelete:function(sid,user_id,dw_id,yh_id,kh_id){
          return resource.save({
            SID:sid,
            USER_ID:user_id,
            ACTION_NAME :  'beanBiz.delete#Ykhxx',
            ACTION_INFO : {
              'yh_id':yh_id,
              'dw_id':dw_id,
              'khId':kh_id
            }
          },function(r){
            if(r.ACTION_RETURN_CODE == "000000") {
              result = r.ACTION_INFO.result;
              $rootScope.$broadcast('DeleteData');
            }
          });
        },
        deleteResult:function(){
          return result;
        }
      }
    });
